﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;

using VSTalk.Engine.Annotations;
using VSTalk.Engine.Core.ClientManager;
using VSTalk.Engine.Core.Context;
using VSTalk.Engine.Utils;
using VSTalk.Engine.ViewModel.Editors.ClientEditor;
using VSTalk.Engine.Windows;
using VSTalk.Model;
using VSTalk.Tools;

namespace VSTalk.Engine.ViewModel.Editors
{
    public class AccountEditorViewModel : INotifyPropertyChanged
    {
        public RelayCommand AddNewClient { get; set; }

        public RelayCommand<Client> EditClient { get; set; }

        public RelayCommand RemoveClient { get; set; }

        public IClientManager ClientManager
        {
            get { return AppServices.Get<IClientManager>(); }
        }

        public static IModelContext ModelContext
        {
            get { return AppServices.Get<IModelContext>(); }
        }

        [UsedImplicitly]
        public ObservableCollection<Client> Clients
        {
            get { return ModelContext.Clients; }
        }

        private Client _selectedClient;

        public Client SelectedClient
        {
            get { return _selectedClient; }
            set
            {
                _selectedClient = value;
                PropertyChanged.Notify(() => SelectedClient);
            }
        }

        public AccountEditorViewModel()
        {
            SetCommands();
        }

        private void SetCommands()
        {
            AddNewClient = new RelayCommand(AddNewClientExecuted);
            RemoveClient = new RelayCommand(RemoveClientExecuted,
                                            () => SelectedClient != null);
            EditClient = new RelayCommand<Client>(EditClientExecuted);
        }

        private void EditClientExecuted(Client client)
        {
            var clientVM = new ClientEditorViewModel(SelectedClient);
            var clientWindow = new ClientEditorWindow();
            var onClose = new Action(() =>
            {
                clientWindow.Close();
                clientVM.StopListen();
            });
            clientWindow.DataContext = clientVM;
            clientVM.Rejected += onClose;
            clientVM.Saved += onClose;
            clientWindow.Show();
        }


        protected void RemoveClientExecuted()
        {
            ClientManager.RemoveClient(SelectedClient);
        }

        protected void AddNewClientExecuted()
        {
            var clientVM = new ClientEditorViewModel();
            var clientWindow = new ClientEditorWindow();
            clientWindow.DataContext = clientVM;
            clientVM.Rejected += clientWindow.Close;
            clientVM.Saved += clientWindow.Close;
            clientWindow.Show();
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}